#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // struct sockaddr_in
#include <arpa/inet.h> // s+truct sockaddr_in
#include <cstring>
#include "err.hpp"
using std::cerr;
using std::endl;
using std::cout;

static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip serverport\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    //1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        cerr << "Create socket error\n";
        exit(SOCKET_ERR);
    }

    //2.客户端不要自己绑定,交给系统自动绑定
    while(true)
    {
        std::string msg;
        cout << "Please Enter# ";
        std::cin >> msg;

        //首次调用系统调用，操作系统自动帮我们绑定端口和ip了
        sendto(sock, msg.c_str(), msg.size(), 0, (struct sockaddr*)&server, sizeof(server));

        char buf[1024];
        socklen_t len = sizeof(server);
        int n = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&server, &len);
        if(n > 0)
        {
            buf[n] = '\0';
            cout << "Server Echo# " << buf << endl;
        }
    }

    return 0;
}